<template>
  <div>
    <b-table
      ref="table"
      :columns="columns"
      :out-loading="loading"
      :request="loadData"
      :del-func="delFunc"
      :disabled="!this.hideBuquBtn() || !!$route.query.businessId"
      bordered
      class="bgFFF"
      :scroll="{ x: 1300 }"
      :export-config="{use:true,select:'物资盘点记录处置明细',all:'物资盘点记录处置明细'}"
    >
      <template
        v-if="state !== 3"
        slot="prefix"
        slot-scope="ref"
      >
        <a-button
          type="primary"
          @click="openDialog()"
        >
          添加行
        </a-button>
      </template>
      <template
        slot="suffix"
        slot-scope="ref"
      >
        <a-button
          type="primary"
          @click="openDialog(downloadApi)"
        >
          标准模板下载
        </a-button>
        <ExcelImportButton
          v-if="state !== 3"
          @handleSubmit="importFunc"
        />
      </template>
      <span
        slot="index"
        slot-scope="text, record, index"
      >{{ index + 1 }}</span>
      <template
        v-for="col in ['unitPrice','bookQuantity','bookAmount','quantity','actualAmount','profitLossQuantity',
                       'profitLossAmount','description']"
        :slot="col"
        slot-scope="text, record, index"
      >
        <div :key="col">
          <template v-if="state !== 3">
            <BaseInput
              v-if="col === 'description'"
              v-model="record[col]"
              @blur="e => handleChange(e.target.value, record, col)"
            />
            <BaseInputNumber
              v-else-if="col === 'unitPrice'"
              v-model="record[col]"
              class="requiredFormItem"
              :precision="2"
              :disabled="col === 'bookAmount' || col === 'actualAmount' || col === 'profitLossQuantity'
                || col === 'profitLossAmount'"
              @blur="e => handleChange(e.target.value, record, col)"
            />
            <BaseInputNumber
              v-else
              v-model="record[col]"
              class="requiredFormItem"
              :precision=" col === 'bookQuantity' || col === 'quantity' ? 3 : 2"
              :disabled="col === 'bookAmount' || col === 'actualAmount' || col === 'profitLossQuantity'
                || col === 'profitLossAmount'"
              @blur="e => handleChange(e.target.value, record, col)"
            />
          </template>
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
    </b-table>
    <material-list-and-dir
      ref="detailDialog"
      @createList="createList"
    />
  </div>
</template>
<script>
import {
  checkDetailList,
  checkDetailDel,
  checkDetailEdit,
  checkDetailAddBatch, downMaterialInventoryExcel
} from '@/api/material/inventory/check'
import { columns } from './insideModel'

export default {
  props: {
    state: {
      type: Number
    },
    id: {
      type: String
    }
  },
  data() {
    return {
      loading: false,
      totalSize: 0,
      columns: columns,
      downloadApi: downMaterialInventoryExcel,
      delFunc: checkDetailDel,
      loadData: params => checkDetailList(Object.assign(params, { baseId: this.id }))
    }
  },
  methods: {
    async importFunc(e) {
      // this.$console(e)
      let newTable = []
      let checkRes = true
      e.map(row => {
        let temp = {}
        for (const rowKey in row) {
          let column = this.columns.find(columnRow => columnRow.title === rowKey)
          if (column) {
            let dataIndex = column.dataIndex
            temp[dataIndex] = row[rowKey]
            if (checkRes && rowKey === '单价(元)' && typeof row[rowKey] !== 'number') checkRes = false
            if (checkRes && rowKey === '账面数' && typeof row[rowKey] !== 'number') checkRes = false
            if (checkRes && rowKey === '实有数' && typeof row[rowKey] !== 'number') checkRes = false
          }
        }
        temp.inventoryId = this.id
        newTable.push(temp)
      })
      if (!checkRes) {
        return this.$noticeWarning('数据格式错误！')
      }
      this.loading = true
      let res = await checkDetailAddBatch(newTable)
      this.loading = false
      if (res.code === this.SUCCESS_CODE) {
        if (res.message === '操作成功！') {
          this.$noticeSuccess('导入成功！')
        } else {
          this.$notification.open({ message: '提示', duration: null, description: () => <pre>{res.message}</pre> })
        }
        this.$refs.table.getData(null, true)
      }
    },
    async openDialog(downloadApi) {
      let allData = []
      if (this.$refs.table.totalSize !== 0) {
        let res = await checkDetailList({
          pageSize: this.$refs.table.totalSize,
          pageNo: 1,
          baseId: this.id
        })
        if (res.code === this.SUCCESS_CODE) {
          allData = res.data
        }
      }
      if (downloadApi) {
        let fileName = '标准模板下载.xlsx'
        this.$refs.detailDialog.download(allData, downloadApi)
      } else {
        this.$refs.detailDialog.open(allData)
      }
    },
    createList(selectRows) {
      let params = []
      selectRows.map(selectRow => {
        params.push({
          materialName: selectRow.materialName,
          materialCode: selectRow.materialCode,
          materialModel: selectRow.specificationModel,
          materialUnit: selectRow.unit,
          materialId: selectRow.id,
          inventoryId: this.id,
          unitPrice: '',
          bookQuantity: '',
          bookAmount: '',
          quantity: '',
          actualAmount: '',
          profitLossQuantity: '',
          profitLossAmount: '',
          description: ''
        })
      })
      checkDetailAddBatch(params).then(res => {
        if (res.code === 200) {
          this.$refs.table.getData(null, true)
        }
      })
    },
    handleChange(value, target, column) {
      target[column] = value
      target['bookAmount'] = target['unitPrice'] * target['bookQuantity']
      target['bookAmount'] = target['bookAmount'].toFixed(2)
      target['actualAmount'] = target['unitPrice'] * target['quantity']
      target['actualAmount'] = target['actualAmount'].toFixed(2)
      target['profitLossAmount'] = target['unitPrice'] * target['profitLossQuantity']
      target['profitLossAmount'] = target['profitLossAmount'].toFixed(2)
      // 避免字符串比对（隐式转换）造成结果错误，因此先将其转换为数字再比较
      const quantityNum = Number.isFinite(Number(target['quantity'])) ? Number(target['quantity']) : 0
      const bookQuantityNum = Number.isFinite(Number(target['bookQuantity'])) ? Number(target['bookQuantity']) : 0
      if (quantityNum < bookQuantityNum) {
        this.$message.warning('实有数不能小于账面数')
        target['quantity'] = 0
        return
      }
      target['profitLossQuantity'] = target['quantity'] - target['bookQuantity']
      target['profitLossQuantity'] = target['profitLossQuantity'].toFixed(2)
      this.save(target)
    },
    save(target) {
      target.baseId = this.id
      try {
        target['bookQuantity'] = Number(target['bookQuantity'])
        target['quantity'] = Number(target['quantity'])
        target['unitPrice'] = Number(target['unitPrice'])
      } catch (e) {
        target['bookQuantity'] = 0
        target['quantity'] = 0
        target['unitPrice'] = 0
      }
      checkDetailEdit(target).then(res => {
        if (res.code !== 200) this.$noticeWarning(res.message)
      })
    }

  }
}
</script>
